package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class AdUserServiceImpl implements AdUserService {
    @Autowired
    private AdUserMapper adUserMapper;
    /**
     * 登录请求
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //todo 1.校验参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //todo 2.根据用户名查询数据库是否存在该用户
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName,dto.getName());
        wrapper.eq(AdUser::getStatus,9);
        AdUser adUser = adUserMapper.selectOne(wrapper);
        if(adUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //todo 3.使用登录密码 + salt盐来生成加密后的密码
        String loginPass = DigestUtils.md5DigestAsHex((dto.getPassword() + adUser.getSalt()).getBytes());
        //todo 4.使用数据库加密密码和登录加密密码进行匹配
        if(!loginPass.equals(adUser.getPassword())){
            //todo 5. 密码不相等。直接返回密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //todo 6.密码匹配，根据用户的Id生成JWT令牌，
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //todo 7.封装返回值响应请求即可
        Map map = new HashMap<>();
        map.put("token",token);
        adUser.setPassword("");
        adUser.setSalt("");
        map.put("user",adUser);
        return ResponseResult.okResult(map);
    }
}
